package com.quotes.io;

import java.util.List;

import org.apache.log4j.Logger;
import com.quotes.datamodell.*;

public class ExcelAdapter {
	private Logger logger = Logger.getLogger(getClass().toString());
	private String fileName;
	
	public ExcelAdapter(String fileName) {
		this.fileName = fileName;
	}
	
	public void saveQuotes(QuotesList list) {
		ExcelHelper excelHelper = new ExcelHelper();
		excelHelper.createNewWorkbook();
		
		for (Quotes quotes : list.getQuotes()) {
			logger.debug("Writing data for symbol " + quotes.getSymbol() + " to worksheet!");
			
			DataTable table = QuotesConverter.toDataTable(quotes);
			excelHelper.createSheet(quotes.getSymbol().getYahooName());
			excelHelper.writeToSheet(quotes.getSymbol().getYahooName(), table, 0, 0);
		}
		
		excelHelper.saveExcelSheet(fileName);
	}
	
	public SymbolList loadSymbols() {
		SymbolList symbols = new SymbolList();
		
		try {
			ExcelHelper excelHelper = new ExcelHelper();
			excelHelper.loadWorkbookFromFile(fileName);
			List<String> sheetNames = excelHelper.getSheetNames();
			
			for (String sheetName : sheetNames) {
				Symbol symbol = new Symbol();
				symbol.setYahooName(sheetName);
				symbols.add(symbol);
			}
		} catch (Exception e) {
			logger.error("Could not load symbol list from excel!", e);
		}
		
		return symbols;
	}
	
	public QuotesList loadQuotes(SymbolList symbols) {
		QuotesList list = new QuotesList();
		
		try {
			ExcelHelper excelHelper = new ExcelHelper();
			excelHelper.loadWorkbookFromFile(fileName);
			
			for (Symbol symbol : symbols.getSymbols()) {
				logger.debug("Reading data from worksheet " + symbol.getYahooName() + "!");
				
				DataTable table = excelHelper.readFromSheet(symbol.getYahooName());
				table.makeFirstRowToHeaders();
				
				Quotes quotes = QuotesConverter.toQuotes(table, symbol);
				list.add(quotes);
			}
		} catch (Exception e) {
			logger.error("Could not load quotes from excel!", e);
		}

		return list;
	}
}
